package com.cly.item.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cly.common.entity.order.dto.OrderDetailDto;
import com.cly.common.entity.item.po.Item;
import com.cly.common.entity.result.Result;
import com.cly.common.exception.CommonException;
import com.cly.item.mapper.ItemMapper;
import com.cly.item.service.ItemService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@Slf4j
public class ItemServiceImpl extends ServiceImpl<ItemMapper, Item> implements ItemService {

    /**
     * 根据id查询商品信息
     *
     * @param ids
     * @return
     */
    @Override
    public List<Item> queryItemsByIds(List<Long> ids) {
        List<Item> items = this.listByIds(ids);
        return items;
    }

    /**
     * 扣减库存
     * 其实直接通过for循环订单，执行sql，也可以，因为每次买的商品不会很多
     *
     * @param orderDetailDtoList
     */
    @Override
    public Result deductStock(List<OrderDetailDto> orderDetailDtoList) {
        String sqlStatement = "com.cly.item.mapper.ItemMapper.deductStock";
        boolean r = false;
        try {
            r = this.executeBatch(orderDetailDtoList,
                    (sqlSession, orderDetailDto) -> sqlSession.update(sqlStatement, orderDetailDto));
        } catch (Exception e) {
            throw new CommonException("更新库存异常，可能库存不足！！！", e);
        }
        if (!r) {
            throw new CommonException("库存不足！！！");
        }
        return Result.success();
    }

    /**
     * 扣减库存
     * 其实直接通过for循环订单，执行sql，也可以
     * @param orderDetailDtoList
     */
    @Override
    public void recoverStock(List<OrderDetailDto> orderDetailDtoList) {
        String sqlStatement = "com.cly.item.mapper.ItemMapper.recoverStock";
        boolean r = false;
        try {
            r = this.executeBatch(orderDetailDtoList,
                    (sqlSession, orderDetailDto) -> sqlSession.update(sqlStatement, orderDetailDto));
        } catch (Exception e) {
            throw new CommonException("恢复库存失败", e);
        }
        if (!r) {
            throw new CommonException("恢复库存失败");
        }
    }

}
